<template>
  <div id="app">
    <div class="header">
      <div class="header_inner">
        <ul class="header_item">
          <li><router-link to="/">首页</router-link></li>
          <li>
            <router-link to="center" v-if="userid != ''">个人中心</router-link>
          </li>
          <li>
            <router-link to="myorder" v-if="userid != ''">我的订单</router-link>
          </li>
          <li style="float:right" v-if="userid == ''">
            <router-link to="register">注册</router-link>
          </li>
          <li style="float:right" v-if="userid == ''">
            <a @click="login">登陆</a>
          </li>
          <li style="float:right" v-else>
            <a @click="logout_btn">{{ username }}：退出</a>
          </li>
        </ul>
      </div>
    </div>
    <div class="main">
      <router-view />
    </div>
    <login :login_form="login_form" />
  </div>
</template>

<script>
import Home from "@/components/Home";
import login from "@/components/common/login";
import { mapState } from "vuex";
export default {
  name: "app",
  components: {
    Home,
    login,
  },
  data() {
    return {
      login_form: false,
    };
  },
  computed: {
    ...mapState({
      username: (state) => state.name,
      userid: (state) => state.user_id,
      userinfo: (state) => state.userinfo,
      logout: (state) => state,
    }),
  },
  methods: {
    logout_btn() {
      this.$store.commit("logout");
    },
    login() {
      this.login_form = true;
    },
    register() {
      console.log("点击注册");
    },
  },
  created() {
    //在页面加载时读取sessionStorage里的状态信息
    if (sessionStorage.getItem("store")) {
      this.$store.replaceState(
        Object.assign(
          {},
          this.$store.state,
          JSON.parse(sessionStorage.getItem("store"))
        )
      );
    }
    //在页面刷新时将vuex里的信息保存到sessionStorage里
    window.addEventListener("beforeunload", () => {
      sessionStorage.setItem("store", JSON.stringify(this.$store.state));
    });

    // 更新登录状态
  },
  watch: {
    userid(n, o) {
      if (this.userid != "") {
        this.login_form = false;
      }
    },
  },
};
</script>

<style>

body {
  padding-right: 15px !important;
  margin: 0;
}

.header {
  height: 65px;
  width: 100%;
  position: fixed;
  z-index: 20;
  top: 0;
  left: 0;
  background-color: ghostwhite;
}

.header_inner {
  margin: auto;
  padding: 0 40px;
}

.header_item {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
}

.header_item li {
  float: left;
}

.header_item li a {
  display: block;
  padding: 18px 16px;
  text-align: center;
  font-size: 20px;
  text-decoration: none;
}

.main {
  margin-top: 65px;
  min-height: 1000px;
}

.main_content {
  width: 94%;
  margin: auto;
  min-height: 1000px;
}
</style>
